<?php

namespace common\models\shop;

use Yii;
use common\helpers\Url;
use common\models\shop\ShopAttachment;

/**
 * This is the model class for table "{{%shop_goods}}".
 *
 * @property int $id
 * @property int $product_id 产品ID
 * @property string $name 商品名称
 * @property string $goods_no 商品编码
 * @property string $cover 商品缩略图
 * @property int $total 总库存
 * @property int $shelf 上架库存
 * @property int $stock 实际库存
 * @property int $min 起订量
 * @property string $price 价格
 * @property string $discount 降价优惠
 * @property string $cost_price 成本价
 * @property string $market_price 市场价
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class ShopGoods extends \common\db\ActiveRecord {

    /**
     * 单品状态
     * 默认0，上架1，删除-1
     */
    CONST STATUS_DEFAULT = 0;
    CONST STATUS_ACTIVE = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%shop_goods}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['product_id', 'total', 'shelf', 'stock', 'min', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['name', 'goods_no'], 'required'],
            [['price', 'discount', 'cost_price', 'market_price'], 'number'],
            [['name'], 'string', 'max' => 50],
            [['goods_no'], 'string', 'max' => 50],
            [['cover'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'product_id' => '产品ID',
            'name' => '商品名称',
            'goods_no' => '商品编码',
            'cover' => '商品缩略图',
            'total' => '总库存',
            'shelf' => '上架库存',
            'stock' => '实际库存',
            'price' => '价格',
            'min' => '起订量',
            'discount' => '降价优惠',
            'cost_price' => '成本价',
            'market_price' => '市场价',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * 关联商品模型
     */
    public function getProduct() {
        return $this->hasOne(ShopProduct::className(), ['id' => 'product_id']);
    }

    /**
     * 关联商品附件模型
     */
    public function getAttachment() {
        return $this->hasMany(ShopAttachment::className(), ['product_id' => 'product_id']);
    }

    /**
     * 关联商品规格视图
     */
    public function getSpecs() {
        return $this->hasMany(\common\models\views\ViewSkuSpec::className(), ['goods_id' => 'id']);
    }

    /**
     * 关联商品规格视图
     */
    public function getActiveSpecs() {
        return $this->getSpecs()->active();
    }

    /**
     * 允许可售库存数量
     * @see 允许可售库存数量计算规则：上架数+实际库存-总数
     * @example shelf+stock-total = 80 + 30 - 100 = 10
     */
    public function getAllowSales() {
        return $this->shelf + $this->stock - $this->total;
    }

    /**
     * 销量
     */
    public function getSales() {
        return $this->total - $this->stock;
    }

    public function getPicture() {
        if ($this->cover) {
            return $this->cover;
        }
        if ($this->product && $this->product->cover) {
            return $this->product->cover;
        }
        return '';
    }

    public function getThumb() {
        if ($this->picture) {
            return Url::attach($this->picture);
        }
        return '';
    }

    public function getSlogan() {
        if ($this->product) {
            return $this->product->slogan;
        }
    }

    public function getGoodsname() {
        if ($this->product) {
            return $this->product->name;
        }
    }

    public function getGoodsdescription() {
        if ($this->product) {
            return $this->product->description;
        }
    }

    public function getAlbum() {
        if ($this->attachment) {
            return $this->attachment;
        }
    }

    /**
     * 商品会员价格
     * @return string
     */
    public function getMemberPrice() {
        $user = Yii::$app->user->identity;
        $discount = 1;
        if ($user) {
            $discount = $user->discount;
        }
        return $this->price * $discount;
    }

    /**
     * 商品市场价格（原价）
     * @return string
     */
    public function getMarketPrice() {
        if ($this->price - $this->memberPrice > 0) {
            return $this->price * 1;
        }
        if ($this->market_price) {
            return $this->market_price * 1;
        }
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        $fields = [
            'id',
            'price' => function() {
                return $this->price * 100;
            },
            'discount' => function() {
                return $this->discount * 100;
            },
            'code' => 'goods_no',
            'discount_price' => function() {
                return 0;
            },
            'stock' => 'allowSales',
            'sales' => 'sales',
            'stock_mode' => function() {
                return 0;
            },
            'is_sell' => function() {
                return null;
            },
            'combin_sku' => function() {
                return false;
            },
            'extend' => function() {
                return null;
            },
            'goods_id' => 'product_id',
        ];
        if (!empty($this->specs)) {
            $text = [];
            foreach ($this->specs as $spec) {
                $fields['s' . $spec->spec_id] = function () use ($spec) {
                    return $spec->spec_value_id;
                };
                $text[] = $spec->spec_value;
            }
            $fields['text'] = function () use ($text) {
                return implode(' ', $text);
            };
        }
        return $fields;
    }

}
